// script.js
// WebSocket连接配置
const wsServer = 'ws://localhost:8081';
let ws;
let logCount = 0;
let blockCount = 0;

// HTML转义函数
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe.toString()
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 初始化WebSocket连接
function initWebSocket() {
    ws = new WebSocket(wsServer);
    
    ws.onopen = function() {
        updateStatus(true, `已连接到 ${wsServer}`);
        document.querySelector('.status').classList.add('connected');
    };
    
    ws.onmessage = function(event) {
        try {
            const logData = JSON.parse(event.data);
            addLogEntry(logData);
            logCount++;
            
            // 更新总请求数
            document.getElementById('total-requests').textContent = logCount;
            
            // 检查是否是拦截的请求
            if (logData.result && logData.result.startsWith("BLOCK")) {
                blockCount++;
                document.getElementById('blocked-requests').textContent = blockCount;
            }
            
        } catch (error) {
            console.error('解析日志数据出错:', error);
        }
    };
    
    ws.onerror = function(error) {
        console.error('WebSocket错误:', error);
        updateStatus(false, '连接出错');
    };
    
    ws.onclose = function() {
        updateStatus(false, '连接已断开，5秒后重连...');
        document.querySelector('.status').classList.remove('connected');
        setTimeout(initWebSocket, 5000);
    };
}

// 更新状态显示
function updateStatus(connected, message) {
    const statusEl = document.querySelector('.status-text');
    statusEl.textContent = message;
}

// 添加日志条目
function addLogEntry(log) {
    const logsList = document.getElementById('logs-list');
    
    // 移除"无日志"提示
    if (logsList.querySelector('.no-logs')) {
        logsList.innerHTML = '';
    }
    
    // 创建新日志条目
    const logEntry = document.createElement('div');
    logEntry.className = 'log-entry';
    
    // 检查是否是拦截请求
    const isBlocked = log.result && log.result.startsWith("BLOCK");
    if (isBlocked) {
        logEntry.classList.add('blocked-entry');
    }
    
    // 根据结果确定样式
    const resultClass = isBlocked ? 'result-blocked' : 
                       log.result === "200" ? 'result-200' :
                       log.result === "404" ? 'result-404' :
                       log.result === "500" ? 'result-500' : '';
    
    // 转义所有动态内容
    logEntry.innerHTML = `
        <div class="ip-address">${escapeHtml(log.client_ip)}</div>
        <div><span class="method method-${log.method}">${escapeHtml(log.method)}</span></div>
        <div>${escapeHtml(log.url)}</div>
        <div class="result ${resultClass}">${escapeHtml(log.result)}</div>
        <div class="port">${escapeHtml(log.port)}</div>
        <div class="timestamp">${escapeHtml(log.timestamp)}</div>
    `;
    
    // 添加到列表顶部
    logsList.insertBefore(logEntry, logsList.firstChild);
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    initWebSocket();
    
    // 设置初始统计值
    document.getElementById('active-clients').textContent = '0';
    
    // 添加搜索功能
    document.getElementById('search-btn').addEventListener('click', function() {
        const searchTerm = document.getElementById('search-input').value.toLowerCase();
        const logEntries = document.querySelectorAll('.log-entry');
        
        logEntries.forEach(entry => {
            const url = entry.children[2].textContent.toLowerCase();
            entry.style.display = url.includes(searchTerm) ? 'grid' : 'none';
        });
    });
    
    // 添加过滤器功能
    document.getElementById('method-filter').addEventListener('change', filterLogs);
    document.getElementById('status-filter').addEventListener('change', filterLogs);
    document.getElementById('ip-filter').addEventListener('input', filterLogs);
    
    function filterLogs() {
        const methodFilter = document.getElementById('method-filter').value;
        const statusFilter = document.getElementById('status-filter').value;
        const ipFilter = document.getElementById('ip-filter').value.toLowerCase();
        
        const logEntries = document.querySelectorAll('.log-entry');
        
        logEntries.forEach(entry => {
            const method = entry.children[1].textContent.trim();
            const status = entry.children[3].textContent.trim();
            const ip = entry.children[0].textContent.toLowerCase();
            
            const methodMatch = methodFilter === 'all' || method === methodFilter;
            const statusMatch = statusFilter === 'all' || 
                              (statusFilter === 'blocked' ? status.startsWith('BLOCK') : status === statusFilter);
            const ipMatch = ipFilter === '' || ip.includes(ipFilter);
            
            entry.style.display = methodMatch && statusMatch && ipMatch ? 'grid' : 'none';
        });
    }
});

document.getElementById('update-firewall').addEventListener('click', function() {
    const blockedPorts = document.getElementById('blocked-ports').value
        .split(',')
        .map(p => parseInt(p.trim()))
        .filter(p => !isNaN(p));
    
    const firewallConfig = {
        type: 'firewall-config',
        blockedPorts: blockedPorts,
        synThreshold: parseInt(document.getElementById('syn-threshold').value),
        banTime: parseInt(document.getElementById('ban-time').value),
        slowTimeout: parseInt(document.getElementById('slow-timeout').value),
        minRate: parseInt(document.getElementById('min-rate').value)
    };
    
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify(firewallConfig));
    }
});